#include "SChangeMatWidget.h"
#include "Widgets/SBoxPanel.h"
#include "Widgets/Input/SButton.h"
#include "Widgets/Input/SEditableTextBox.h"
#include "Widgets/Layout/SBox.h"
#include "Widgets/Text/STextBlock.h"
#include "ContentBrowserModule.h"
#include "IContentBrowserSingleton.h"
#include "Misc/FileHelper.h"

#define LOCTEXT_NAMESPACE "FChangeMatModule"

void SChangeMatWidget::Construct( const FArguments& Args )
{
	OnExecute = Args._OnOkButtonClicked;

	FContentBrowserModule& CB = FModuleManager::LoadModuleChecked<FContentBrowserModule>( "ContentBrowser" );
	IContentBrowserSingleton& CBInstance = CB.Get( );

	FPathPickerConfig SrcPathPickerConfig;
	//PickerConfig.bAllowClassesFolder = true;
	SrcPathPickerConfig.OnPathSelected = FOnPathSelected::CreateSP( this, &SChangeMatWidget::SrcPathSelected );
	TSharedRef<SWidget> SrcPathPickerWidget = CBInstance.CreatePathPicker( SrcPathPickerConfig );

	FPathPickerConfig DestPathPickerConfig;
	DestPathPickerConfig.OnPathSelected = FOnPathSelected::CreateSP( this, &SChangeMatWidget::DestPathSelected );
	TSharedRef<SWidget> DestPathPickerWidget = CBInstance.CreatePathPicker( DestPathPickerConfig );

	ChildSlot
		[
			SNew( SBox )
			[
				SNew( SHorizontalBox )
				+ SHorizontalBox::Slot( )
					.FillWidth( 0.5f )
					[
						SrcPathPickerWidget
					]
				+ SHorizontalBox::Slot( )
					[
						SNew( SVerticalBox )
						+ SVerticalBox::Slot( )
							.FillHeight( 0.1f )
							[
								SNew( SButton )
									.OnClicked( this, &SChangeMatWidget::OnClicked )
									[
										SNew( STextBlock )
											.Text( LOCTEXT( "Ok", "<<< 以右边替换左边" ) )
									]
							]
						+ SVerticalBox::Slot( )
							[
								SAssignNew( LogWnd, SEditableText )
									.IsReadOnly( true )
									.Text( LOCTEXT( "Result", "Result" ) )
							]
					]
				+ SHorizontalBox::Slot()
					.FillWidth( 0.5f )
					[
						DestPathPickerWidget
					]
			]
		];
}

void SChangeMatWidget::SrcPathSelected( const FString& Path )
{
	SrcPathPicked = Path;
}

void SChangeMatWidget::DestPathSelected( const FString& Path )
{
	DestPathPicked = Path;
}

void SChangeMatWidget::ShowLog( const FString& LogFilePath )
{
	TArray<FString> RawLines;
	if (FFileHelper::LoadFileToStringArray( RawLines, *LogFilePath ))
	{
		FString Result;
		for (int32 i = 0; i < RawLines.Num( ); ++i)
		{
			Result.Append( RawLines[i] );
			Result.Append( TEXT( "\n" ) );
		}
		LogWnd->SetText( FText::FromString( Result ) );
	}
}

FReply SChangeMatWidget::OnClicked( )
{
	LogWnd->SetText( FText::GetEmpty( ) );

	if (!SrcPathPicked.IsEmpty( ) && !DestPathPicked.IsEmpty( ) && SrcPathPicked != DestPathPicked)
	{
		OnExecute.ExecuteIfBound( SrcPathPicked, DestPathPicked );
	}
	else
	{
		OnExecute.ExecuteIfBound( "", "" );
	}

	return FReply::Handled( );
}

#undef LOCTEXT_NAMESPACE
